package com.ruoyi.data.domain.listener;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.ClassificationType;
import com.ruoyi.common.excel.ExcelListener;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ValidatorUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.data.domain.DataList;
import com.ruoyi.data.domain.bo.DataClassificationBo;
import com.ruoyi.data.domain.bo.DataListBo;
import com.ruoyi.data.domain.vo.DataClassificationVo;
import com.ruoyi.data.domain.vo.DataListImportVo;
import com.ruoyi.data.service.IDataClassificationService;
import com.ruoyi.data.service.IDataListService;
import com.ruoyi.system.domain.vo.SysUserImportVo;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据导入
 *
 * @author Lion Li
 */
@Slf4j
public class DataListImportListener extends AnalysisEventListener<DataListImportVo> implements ExcelListener<DataListImportVo> {

    private IDataListService iDataListService;

    private IDataClassificationService iDataClassificationService;


    private final Boolean isUpdateSupport;

    private final String operName;

    private final Long userId;
    private final String pid;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    List<DataClassificationVo> dataClassificationVos;

    public DataListImportListener(Boolean isUpdateSupport) {
        this.iDataListService = SpringUtils.getBean(IDataListService.class);
        this.iDataClassificationService = SpringUtils.getBean(IDataClassificationService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operName = LoginHelper.getUsername();
        this.userId = LoginHelper.getUserId();
        this.pid = IdUtil.fastSimpleUUID();
        DataClassificationBo d = new DataClassificationBo();
        this.dataClassificationVos = iDataClassificationService.selectClassificationByIdUserId(userId, d);

    }
    private static final int BATCH_SIZE=2000;
    private List <DataList> inList= new ArrayList<>();


    @Override
    @Transactional
    public void invoke(DataListImportVo dataListImportVo, AnalysisContext context) {


        DataList dataListBo = BeanUtil.toBean(dataListImportVo, DataList.class);

        //查询分类是否存在
        String classificationName = dataListImportVo.getClassificationName();
        List<Long> classificationIdList = dataClassificationVos.stream()
            .filter(dataClassificationVo -> StringUtils.equals(classificationName, dataClassificationVo.getClassificationName()))
            .map(DataClassificationVo::getClassificationId).collect(Collectors.toList());

        //如果分类存在
        if (CollectionUtil.isNotEmpty(classificationIdList)){
            dataListBo.setPid(pid);
            dataListBo.setClassificationId(classificationIdList.get(0));
            dataListBo.setUserId(userId);
            dataListBo.setCreateBy(operName);
            dataListBo.setStatus("0");
            inList.add(dataListBo);
            successNum++;

        } else {
            //分类不存在
            failureNum++;
            failureMsg.append("<br/>").append(failureNum).append("、分类 ").append(classificationName).append(" 不存在");
        }

        if(inList.size()>=BATCH_SIZE){
            //读取到的数据大于等于500  插入500条数据到mysql数据库
            iDataListService.batchInsertByBo(inList);
            //清空集合
            inList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //读取到的数据大于等于500  插入500条数据到mysql数据库
        iDataListService.batchInsertByBo(inList);
        //清空集合
        inList.clear();
    }

    @Override
    public ExcelResult<DataListImportVo> getExcelResult() {
        return new ExcelResult<DataListImportVo>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    //throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }

                return successMsg.toString();
            }

            @Override
            public List<DataListImportVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
